﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomerMgr.Data;
using Telerik.Web.UI;
using System.Data;
using System.Collections;

namespace CustomerMgr.Web
{
    public partial class Customer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = CustomerFactory.SelectAll();
        }
        protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            int cusId = (int)editedItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"];
            CustomerMgr.Data.Models.Customer cus = CustomerFactory.SelectOne(cusId);

            TextBox txtName = (TextBox)editedItem.FindControl("txtName");
            TextBox txtDescription = (TextBox)editedItem.FindControl("txtDescription");
            cus.Name = txtName.Text;
            cus.Description = txtDescription.Text;
            if (CustomerFactory.Update(cus))
            {
                RadGrid1.Rebind();
            }

        }
        protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            CustomerMgr.Data.Models.Customer cus = new Data.Models.Customer();

            TextBox txtName = (TextBox)editedItem.FindControl("txtName");
            TextBox txtDescription = (TextBox)editedItem.FindControl("txtDescription");
            cus.Name = txtName.Text;
            cus.Description = txtDescription.Text;
            if (CustomerFactory.Insert(cus)!=null)
            {
                editedItem.Edit = false;
                
                RadGrid1.Controls.Add(new LiteralControl(string.Format("Thêm mới thành công thông tin khách hàng {0}", txtName.Text)));
                RadGrid1.Rebind();
            }
        }

        protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
        {
            int cusId = (int)(e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"];
            CustomerMgr.Data.Models.Customer cus = CustomerFactory.SelectOne(cusId);
            if (CustomerFactory.Delete(cus))
            {
                RadGrid1.Rebind();
            }
        }
    }
}